/**
 * Created by wangzilong on 2017/4/11.
 */
import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Image,
    ScrollView,
    TouchableOpacity,
    TextInput,
    Navigator,
    Platform,
    Button,
    InteractionManager,
    ActivityIndicator,
    ListView
} from 'react-native';
import ImageWrapper from '../components/ImageWrapper';
import NavigationBar from '../components/NavigationBar';
import { MapView, MapTypes, MapModule, Geolocation, PoiSearch } from '@zzzkk2009/react-native-baidu-map';
var Dimensions = require('Dimensions');
const { width, height } = Dimensions.get('window');
const MAP_HEIGHT = height - 20

export default class BaiduMap extends Component{
    constructor(props) {
        super(props);
        var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        this.addressList = [];
        this.pageNum = 1;
        this.state = {
            dataSource: ds.cloneWithRows(this.addressList),
            marker:null,
            zoom:15,
            searchText:'',
            shopAddress:'',
            center:{
                latitude:40.057406655722,
                longitude:116.29644071728,
            },
            showList:false,
            inputValue:'',
            showDelete:false,
            showBottom:false,
            uid:'',
        }
        
    }
    componentDidMount() {
        Geolocation.getCurrentPosition()
        .then(data => {
            // console.log('getCurrentPosition.data===', data)
            // alert(JSON.stringify(data))
            this.setState({
                center: {
                    latitude: data.latitude,
                    longitude: data.longitude,
                },
            })

            if (Platform.OS == 'ios') {
                this.updateInfoByLatLng(data.latitude, data.longitude)
            }else {
                this.setState({
                    // shopAddress: data.address,
                    locationCity: data.city,
                    // currentDistrict: data.district
                })
            }
        // console.log('getCurrentPosition.this.state===', this.state)

        })
        .catch(e =>{
            this.setState({
                locationCity:'北京市'
            })
            console.warn(e, 'error')
        })
    }

    renderAddress(rowData, sectionID, rowID){
        return(
            <TouchableOpacity onPress={()=>this.choseAddress(rowData)}>
                <View style={{paddingLeft:10,paddingRight:10,paddingTop:2,paddingBottom:2}}>
                    <Text>{rowData.address + rowData.name}</Text>
                </View>
            </TouchableOpacity>
        )
    }

    render() {
        return (
            <View style={styles.container}>
                <NavigationBar 
                    style={{position:'absolute',top:0,left:0}}
                    leftPress={()=>this.goBack()}
                    leftIcon={'left'} 
                    titleText={'店铺位置'}/>
                <View style={{width:width-20,borderWidth:1,borderColor:'#ccc',position:'absolute',top:50,left:10,zIndex:100,backgroundColor:'#fff',flexDirection:'row',alignItems:'center',paddingRight:10}}>
                    <TextInput 
                        style={{height:30,paddingLeft:10,paddingTop:3,paddingBottom:3,flex:1,fontSize:12}}
                        underlineColorAndroid={'transparent'}
                        placeholder={'请输入搜索地址'}
                        onChangeText={(text)=>this.searchAddress(text)}
                        defaultValue={this.state.inputValue?this.state.inputValue:this.state.searchText}
                        ref={(e)=>this._input=e}/>
                    {this.state.showDelete?<TouchableOpacity onPress={()=>this.deleteText()}>
                        <ImageWrapper icon={'iconDelete'} width={20} height={20}/>
                    </TouchableOpacity>:<View></View>}
                </View>
                {this.state.showList?<View style={{width:width-20,borderWidth:1,borderColor:'#ccc',position:'absolute',top:80,left:10,zIndex:100,backgroundColor:'#fff',justifyContent:'center'}}>
                    <ListView
                        style={{maxHeight:200}}
                        dataSource={this.state.dataSource}
                        renderRow={(rowData, sectionID, rowID) => this.renderAddress(rowData, sectionID, rowID)}
                        onEndReachedThreshold={2}
                        onEndReached={()=>this.loadMore()}/>
                </View>:<View></View>}
                <MapView
                  style={styles.map}
                  onMapStatusChangeFinish={this.changeFinished.bind(this)}
                  onRegionDidChangeAnimated={this.changeAnimated.bind(this)}
                  center={this.state.center}
                  marker={this.state.marker}
                  zoom={this.state.zoom}
                  onMapClick={()=>{this.setState({showList:false})}}/>

                <Image
                  style={[styles.mapMarker, this.state.mapMarkerPos]}
                  source={require("../img/icon/location.png")}
                  onLayout={this.onMapMarkerImageLayout.bind(this)}/>
                {this.state.showBottom?<View style={styles.bottomInput}>
                    <View style={styles.inputBox}>
                        <Text>店铺名称:</Text>
                        <TextInput
                            style={styles.input}
                            underlineColorAndroid={'transparent'}
                            placeholder={'请输入商户名称'}/>
                    </View>
                    <View style={styles.inputBox}>
                        <Text>店铺地址:</Text>
                        <TextInput
                            style={styles.input}
                            underlineColorAndroid={'transparent'}
                            placeholder={'商户地址'}
                            defaultValue={this.state.shopAddress}/>
                    </View>
                    <TouchableOpacity onPress={()=>this.finishBtn()}>
                        <View style={{backgroundColor:'#6BE3C7',height:30,justifyContent:'center',alignItems:'center',margin:3}}>
                            <Text style={{color:'#fff'}}>完成</Text>
                        </View>
                    </TouchableOpacity>
                </View>:<View></View>}

            </View>
        )
    }

    goBack(){
        this.props.navigation.goBack();
    }

    changeAnimated(e) {
        // console.log('_onRegionDidChangeAnimated4Ios.e====', e)
        this.changeFinished(e)
    }
    
    changeFinished(e){
        // alert(JSON.stringify(e))
        this.updateInfoByLatLng(e.target.latitude, e.target.longitude);
        
    }

    updateInfoByLatLng(latitude, longitude) {
        var $this = this;
        Geolocation.reverseGeoCode(latitude, longitude)
        .then((response) => {
            alert(JSON.stringify(response))
            // alert(latitude+'//'+longitude)
            $this.setState({
                shopAddress:response.poiInfos[0].address+response.poiInfos[0].name,
                uid:response.poiInfos[0].uid,
                showBottom:true,
                center:{
                    latitude:latitude,
                    longitude:longitude,
                }
            })
        
        })
        .catch(e =>{
            console.warn(e, 'error')
        })
    }

    onMapMarkerImageLayout(event) {
        // alert(JSON.stringify(event))
        this.setState({
            mapMarkerPos: {
                left: (width ) / 2 -12,
                top: height / 2 -12 ,
            }
        })
    }

    searchPress(){
        var $this = this;
        this.pageNum = 1;
        PoiSearch.searchInCityProcess(this.state.locationCity,this.state.searchText, 1)
        .then(data => {
            if(data.message=='成功'){

                var arr = data.poiResult.poiInfos;
                $this.addressList = data.poiResult.poiInfos;
                $this.setState({
                    showList:true,
                    searchText:text,
                    dataSource: $this.state.dataSource.cloneWithRows(arr),
                    inputValue:''
                })

            }else{
                $this.setState({
                    showList:false,
                    searchText:text,
                    inputValue:''
                })
            }
            // alert(JSON.stringify(data))

        })
        .catch(e =>{
            console.warn(e, 'error')
            // alert(2)
        })
    }

    searchAddress(text){
        var $this = this;
        this.pageNum = 1;
        this.setState({
            showDelete:(text==''?false:true)
        })
        PoiSearch.searchInCityProcess('北京市',text, 1)
        .then(data => {
            // alert(1)
            // console.log('searchInCityProcess.data===', data)
            // $this.setState({
            //     marker:{
            //         longitude:data.poiResult.longitude,
            //         latitude:data.poiResult.latitude,
            //         title:''
            //     }
            // })
            if(data.message=='成功'){
                var arr = data.poiResult.poiInfos;
                alert(JSON.stringify(data))
                $this.addressList = data.poiResult.poiInfos;
                $this.setState({
                    showList:true,
                    searchText:text,
                    dataSource: $this.state.dataSource.cloneWithRows(arr),
                    inputValue:'',
                    showDelete:(text==''?false:true)
                })
            }else{
                $this.setState({
                    showList:false,
                    searchText:text,
                    inputValue:'',
                    showDelete:(text==''?false:true)
                })
            }
            // alert(JSON.stringify(data))

        })
        .catch(e =>{
            console.warn(e, 'error')
            // alert(2)
        })
        
    }

    loadMore(){
        var $this = this;
        this.pageNum = ++this.pageNum;
        var text = this.state.searchText;
        PoiSearch.searchInCityProcess('北京市',text, this.pageNum)
        .then(data => {
            if(data.message=='成功'){
                var arr = data.poiResult.poiInfos;
                $this.addressList = $this.addressList.concat(arr);
                $this.setState({
                    showList:true,
                    searchText:text,
                    dataSource: $this.state.dataSource.cloneWithRows($this.addressList),
                    inputValue:''
                })
            }else{
                $this.setState({
                    showList:false,
                    searchText:text,
                    inputValue:''
                })
            }
            // alert(JSON.stringify(data))

        })
        .catch(e =>{
            console.warn(e, 'error')
            // alert(2)
        })
    }

    choseAddress(rowData){
        // alert(JSON.stringify(rowData))
        this.setState({
            inputValue:rowData.address + rowData.name,
            searchText:rowData.address + rowData.name,
            center:{
                latitude:rowData.latitude,
                longitude:rowData.longitude,
            },
            uid:rowData.uid,
            showList:false,
            shopAddress:rowData.address + rowData.name,
            showDelete:true,
            showBottom:true
        })
    }

    deleteText(){
        this._input.clear();
        this.setState({
            showDelete:false,
            showList:false
        })
    }

    finishBtn(){
        var obj = {};
        obj.address = this.state.shopAddress;
        obj.lat = this.state.center.latitude;
        obj.lng = this.state.center.longitude;
        obj.uid = this.state.uid;
        this.props.navigation.state.params.getLocation(obj);
        this.goBack();
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        ...Platform.select({
            ios: {
                marginTop: 20,
            },
            android: {
                marginTop: 0
            }
        }),
    },
    mapMarker: {
        position: 'absolute',
        width: 24,
        height: 24,
        zIndex:1000,
    },
    map: {
        width: width,
        ...Platform.select({
            ios: {
                height: height-20
            },
            android: {
                height: height
            }
        }),
        
    },
    bottomInput:{
        position:'absolute',
        left:0,
        bottom:0,
        backgroundColor:'#fff',
        borderTopColor:'#ccc',
        borderTopWidth:1,
        width:width
    },
    inputBox:{
        height:30,
        alignItems:'center',
        borderBottomWidth:1,
        borderBottomColor:'#eee',
        flexDirection:'row',
        paddingLeft:10
    },
    input:{
        paddingTop:0,
        paddingBottom:0,
        paddingLeft:10,
        paddingRight:10,
        fontSize:12,
        flex:1
    }
})